package com.cositas.dulces.lp.promo2012;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cositas.dulces.lp.promo2012.dbentities.Participant;
import com.cositas.dulces.lp.promo2012.dbentities.Recommendation;
import com.cositas.dulces.lp.promo2012.utils.ActionsPoints;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class JoinPromoAction implements Action {

	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws IOException, EntityNotFoundException, ServletException {
		String fbid = req.getParameter(Participant.field_fbid);
		String fbname= req.getParameter(Participant.field_fbname);
		Key k = KeyFactory.createKey(Participant.entity_name, fbid);
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		// busco si no es participante
		try {
			Entity entity = datastore.get(k);
			req.getRequestDispatcher("./tab.jsp").forward(req, resp);
			return;
		} catch (EntityNotFoundException e) {
			// TODO: handle exception
			// si no era participante, lo hago participar
			Entity participant = new Entity(k);
			participant.setProperty(Participant.field_fbname, fbname);
			participant.setProperty(Participant.field_points, String.valueOf(ActionsPoints.JOIN_POINTS));
			datastore.put(participant);
		}
		// Busco los que lo recomendaron asi les doy puntos
		Query query = new Query(Recommendation.entity_name).addFilter(Recommendation.field_tofbid, FilterOperator.EQUAL, fbid);
		List<Entity> recommendation = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1000));
		for (Entity e : recommendation) {
			String fbidRecommender = (String)e.getProperty(Recommendation.field_fromfbid);
			Key keyRec = KeyFactory.createKey(Participant.entity_name, fbidRecommender);
			Entity participant = datastore.get(keyRec);
			Integer account = Integer.valueOf((String)participant.getProperty(Participant.field_points));
			account = account + ActionsPoints.JOIN_RECOMMENDATION_POINTS;
			participant.setProperty(Participant.field_points, account.toString());
			datastore.put(participant);
		}
		req.getRequestDispatcher("./tab.jsp").forward(req, resp);
	}
}
